import 'dart:convert';
import 'dart:typed_data';
import 'dart:io';
import 'package:flutter/material.dart';

class ImageCacheService {
  static final ImageCacheService _instance = ImageCacheService._internal();
  factory ImageCacheService() => _instance;
  ImageCacheService._internal();

  // 缓存解码后的图片数据
  final Map<String, Uint8List> _imageDataCache = {};
  
  // 缓存ImageProvider实例
  final Map<String, ImageProvider> _imageProviderCache = {};

  /// 获取缓存的ImageProvider，如果没有缓存则创建并缓存
  ImageProvider? getImageProvider(String? albumArtUri) {
    if (albumArtUri == null || albumArtUri.isEmpty) {
      return null;
    }

    // 如果已经缓存了ImageProvider，直接返回
    if (_imageProviderCache.containsKey(albumArtUri)) {
      return _imageProviderCache[albumArtUri];
    }

    ImageProvider? provider;

    try {
      if (albumArtUri.startsWith('data:image/')) {
        // 处理base64数据
        if (_imageDataCache.containsKey(albumArtUri)) {
          // 使用缓存的数据
          provider = MemoryImage(_imageDataCache[albumArtUri]!);
        } else {
          // 解析并缓存数据
          final uri = Uri.parse(albumArtUri);
          final imageData = uri.data!.contentAsBytes();
          _imageDataCache[albumArtUri] = imageData;
          provider = MemoryImage(imageData);
        }
      } else if (albumArtUri.startsWith('http')) {
        // 网络图片
        provider = NetworkImage(albumArtUri);
      } else {
        // 本地文件
        provider = FileImage(File(albumArtUri));
      }

      // 缓存ImageProvider
      if (provider != null) {
        _imageProviderCache[albumArtUri] = provider;
      }
    } catch (e) {
      print('ImageCacheService: 处理图片失败: $e');
      return null;
    }

    return provider;
  }

  /// 预加载图片到缓存
  void preloadImage(String? albumArtUri) {
    if (albumArtUri != null && albumArtUri.isNotEmpty) {
      getImageProvider(albumArtUri);
    }
  }

  /// 清理缓存
  void clearCache() {
    _imageDataCache.clear();
    _imageProviderCache.clear();
  }

  /// 清理指定图片的缓存
  void clearImageCache(String albumArtUri) {
    _imageDataCache.remove(albumArtUri);
    _imageProviderCache.remove(albumArtUri);
  }

  /// 获取缓存大小信息
  Map<String, int> getCacheInfo() {
    return {
      'imageDataCacheSize': _imageDataCache.length,
      'imageProviderCacheSize': _imageProviderCache.length,
    };
  }
} 